package tv.ismar.homepage.fragment;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.os.IBinder;
import android.os.RemoteException;
import android.support.v4.app.Fragment;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;

import com.google.gson.Gson;

import java.util.HashMap;

import cn.ismartv.truetime.TrueTime;
import cn.ismartv.voice.IClientVoiceControlAidlInterface;
import tv.ismar.app.AppConstant;
import tv.ismar.app.BaseActivity;
import tv.ismar.app.core.PageIntent;
import tv.ismar.app.core.SimpleRestClient;
import tv.ismar.app.core.Source;
import tv.ismar.app.entity.ChannelEntity;
import tv.ismar.app.entity.HomePagerEntity;
import tv.ismar.app.entity.HomePagerEntity.Carousel;
import tv.ismar.app.entity.HomePagerEntity.Poster;
import tv.ismar.app.player.CallaPlay;
import tv.ismar.app.util.Utils;
import tv.ismar.homepage.R;
import tv.ismar.homepage.view.HomePageActivity;

import static tv.ismar.app.AppConstant.VoiceControlInstruct.VOICE_CONTROL_BROADCAST_FILTER;

public class ChannelBaseFragment extends Fragment {
    private static long smart_post_occour_error_time = 0;
    protected ChannelEntity channelEntity;
    protected HomePageActivity mContext;
    protected boolean scrollFromBorder;
    protected View mLeftTopView;
    protected View mLeftBottomView;
    protected View mRightTopView;
    protected View mRightBottomView;
    protected boolean isRight;
    protected String bottomFlag;
    protected HashMap<String, String> dataMap;

    protected HomePagerEntity mHomePagerEntity;

    public String snToken = "";

    public void setRight(boolean isRight) {
        this.isRight = isRight;
    }

    public void setBottomFlag(String bottomFlag) {
        this.bottomFlag = bottomFlag;
    }

    public ChannelEntity getChannelEntity() {
        return channelEntity;
    }

    public void setScrollFromBorder(boolean scrollFromBorder) {
        this.scrollFromBorder = scrollFromBorder;
    }

    public void setChannelEntity(ChannelEntity channelEntity) {
        this.channelEntity = channelEntity;
        AppConstant.purchase_page = "homepage";
        AppConstant.purchase_channel = channelEntity.getChannel();
        AppConstant.purchase_entrance_channel = channelEntity.getChannel();
        AppConstant.purchase_entrance_page = "homepage";
    }

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        mContext = (HomePageActivity) activity;
        snToken = ((HomePageActivity) activity).snToken;

    }

    @Override
    public void onDetach() {
        mContext = null;
        ItemClickListener = null;
        super.onDetach();
    }

    @Override
    public void onResume() {
        super.onResume();
        if (null != channelEntity && !TextUtils.isEmpty(channelEntity.getChannel())) {
            mContext.channelRequestFocus(channelEntity.getChannel());
        }
        if (mHomePagerEntity!=null){
            setVoiceControlContext("homepage", new Gson().toJson(mHomePagerEntity));
        }
    }

    protected View.OnClickListener ItemClickListener = new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Object o = view.getTag(R.id.view_position_tag);
            if (o != null) {
                int viewPosition = (int) o;
                AppConstant.purchase_tab = String.valueOf(viewPosition);
                Log.d("ChannelBaseFragment", "view position: " + AppConstant.purchase_tab);
            }


            String url = null;
            String contentMode = null;
            String title = null;
            String mode_name = null;
            String channel = "homepage";
            String type;
            int pk;
            boolean expense = false;
            int position = -1;
            if (channelEntity != null)
                if (channelEntity.getChannel() != null && !("".equals(channelEntity.getChannel()))) {
                    channel = channelEntity.getChannel();
                    if ("launcher".equals(channelEntity.getChannel())) {
                        channel = "homepage";
                    }
                }
            BaseActivity.baseChannel = channel;
            if (view.getTag() instanceof Poster) {
                Poster new_name = (Poster) view.getTag();
                contentMode = new_name.getContent_model();
                url = new_name.getUrl();
                title = new_name.getTitle();
                mode_name = new_name.getModel_name();
                expense = new_name.isExpense();
                position = new_name.getPosition();
            } else if (view.getTag(R.drawable.launcher_selector) instanceof Carousel) {
                Carousel new_name = (Carousel) view.getTag(R.drawable.launcher_selector);
                contentMode = new_name.getContent_model();
                url = new_name.getUrl();
                title = new_name.getTitle();
                mode_name = new_name.getModel_name();
                expense = new_name.isExpense();
                position = new_name.getPosition();
            }
            type = mode_name;
            Intent intent = new Intent();
            intent.putExtra("channel", channel);
            if (url == null) {
                intent.setAction("tv.ismar.daisy.Channel");
                title = channelEntity.getName();
                pk = SimpleRestClient.getItemId(channelEntity.getUrl(), new boolean[1]);
                intent.putExtra("title", channelEntity.getName());
                intent.putExtra("url", channelEntity.getUrl());
                intent.putExtra("portraitflag", channelEntity.getStyle());
                mContext.startActivity(intent);
            } else {
                pk = SimpleRestClient.getItemId(url, new boolean[1]);
                Log.i("basefragment", url);
                if (contentMode.contains("gather")) {
                    int itemPk = Utils.getItemPk(url);
                    PageIntent intent1 = new PageIntent();
                    intent1.toSubject(mContext, contentMode, itemPk, title, BaseActivity.baseChannel, "");
                } else if ("item".equals(mode_name)) {
                    pk = SimpleRestClient.getItemId(url, new boolean[1]);
                    PageIntent pageIntent = new PageIntent();
                    pageIntent.toDetailPage(mContext, "homepage", pk);
                } else if ("topic".equals(mode_name)) {
                    intent.putExtra("url", url);
                    intent.setAction("tv.ismar.daisy.Topic");
                    mContext.startActivity(intent);
                } else if ("section".equals(mode_name)) {
                    intent.putExtra("title", title);
                    intent.putExtra("itemlistUrl", url);
                    intent.putExtra("lableString", title);
                    intent.putExtra("pk", pk);
                    intent.setAction("tv.ismar.daisy.packagelist");
                    mContext.startActivity(intent);
                } else if ("package".equals(mode_name)) {
                    intent.setAction("tv.ismar.daisy.packageitem");
                    intent.putExtra("url", url);
                    mContext.startActivity(intent);
                } else if ("clip".equals(mode_name)) {
                    int itemPk = Utils.getItemPk(url);
                    PageIntent pageIntent = new PageIntent();
                    pageIntent.toPlayPage(mContext, itemPk, -1, Source.HOMEPAGE);
//                    if (tool == null)
//                        tool = new InitPlayerTool(mContext);
//                    tool.channel = channelEntity.getChannel();
//                    tool.fromPage = "homepage";
//                    tool.initClipInfo(url, InitPlayerTool.FLAG_URL);
                }
            }
            CallaPlay play = new CallaPlay();
            play.homepage_vod_click(pk, title, channel, position, type);
        }
    };

    public void playCarouselVideo() {

    }

    public void refreshData() {
    }

    protected static void setSmartPostErrorTime() {
        smart_post_occour_error_time = TrueTime.now().getTime();
    }

    protected static long getSmartPostErrorTime() {
        return smart_post_occour_error_time;
    }


    BroadcastReceiver mVoiceControlBroadcast = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String domain = intent.getStringExtra("domain");
            switch (domain) {
                case "channel":
                    String channel = intent.getStringExtra("channel");
                    if ("more".equals(channel)) {
                        handlerMoreClick();
                    }
                    break;
                case "video":
                    String name = intent.getStringExtra("name");
                    String action = intent.getStringExtra("action");
                    int pk = intent.getIntExtra("pk", 0);
                    voiceControlToPlayer(action, name, pk);
                    break;
            }

        }
    };


    protected void handlerMoreClick() {

    }

    protected void handerSearchVideo(String videoName) {
        Intent intent = new Intent();
        intent.setAction("tv.ismar.searchresult");
        intent.putExtra("raw", videoName);
        startActivity(intent);
    }

    private void voiceControlToPlayer(String action, String videoName, int pk) {
        if ("search".equals(action)) {
            handerSearchVideo(videoName);
        } else {
            if (pk != 0) {
                Intent playerIntent = new Intent();
                playerIntent.setAction("tv.ismar.daisy.Player");
                playerIntent.putExtra("pk", pk);
                if (getActivity() != null) {
                    getActivity().startActivity(playerIntent);
                }
            } else {
                handerSearchVideo(videoName);
            }
        }
    }

    private void registerReceiver() {
        IntentFilter intentFilter = new IntentFilter(VOICE_CONTROL_BROADCAST_FILTER);
        if (getActivity() != null) {
            getActivity().registerReceiver(mVoiceControlBroadcast, intentFilter);
        }
    }

    private void unRegisterReceiver() {
        if (getActivity() != null) {
            getActivity().unregisterReceiver(mVoiceControlBroadcast);
        }
    }

    @Override
    public void onStart() {
        super.onStart();
        registerReceiver();
        Intent intent = new Intent();
        intent.setAction("cn.ismartv.voice.launcher_service");
        intent.setPackage("cn.ismartv.voice");
        getActivity().bindService(intent, mServiceConnection, Context.BIND_AUTO_CREATE);
    }

    @Override
    public void onStop() {
        unRegisterReceiver();
        getActivity().unbindService(mServiceConnection);
        super.onStop();
    }


    private IClientVoiceControlAidlInterface mVoiceControl;

    private ServiceConnection mServiceConnection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            mVoiceControl = IClientVoiceControlAidlInterface.Stub.asInterface(service);
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
        }
    };

    protected void setVoiceControlContext(String context, String data) {
        if (mVoiceControl != null) {
            try {
                mVoiceControl.setVoiceControlContext(context, data);
            } catch (RemoteException e) {
                e.printStackTrace();
            }
        }
    }
}
